package com.hexiang.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
@Slf4j
public class TagFilterProducer {

    private String topic = "test_tag_filter_topic";

    private String producerGroup = "tag_filter_producer_group";

    private String nameServer = "127.0.0.1:9876";

    private DefaultMQProducer defaultMQProducer;


    @PostConstruct
    public void start() throws MQClientException {
        defaultMQProducer = new DefaultMQProducer(producerGroup,getAclRPCHook());
        defaultMQProducer.setNamesrvAddr(nameServer);
        defaultMQProducer.start();
    }

    @PreDestroy
    public void shutdown() {
        defaultMQProducer.shutdown();
    }

    RPCHook getAclRPCHook() {
        return new AclClientRPCHook(new SessionCredentials("rocketmq_u1", "12345678"));
    }
    /**
     * 发送带tag的消息
     */
    public void sendMsgByTag() {
        try {
            String[] tags = new String[]{"TagA", "TagB", "TagC"};

            for (int i = 0; i < 3; i++) {
                Message msg = new Message(topic,
                        tags[i % tags.length],
                        "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = defaultMQProducer.send(msg);
                log.warn("sendResult " + sendResult.getMsgId());
            }
        } catch (Exception e) {
            log.error("sendTagMsgErr", e);
        }

    }

}